package zhongbo.java.air.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

@Configuration
public class JacksonConfig {

    public static class CustomDateDeserializer extends JsonDeserializer<Date> {
        private static final SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US);
        private static final SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
        private static final SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String date = p.getText();
            if (date == null || date.isEmpty()) {
                return null; // 返回null，避免抛出NumberFormatException
            }
            try {
                return dateFormat1.parse(date);
            } catch (ParseException e) {
                try {
                    return dateFormat2.parse(date);
                } catch (ParseException e1) {
                    try {
                        return dateFormat3.parse(date);
                    } catch (ParseException e2) {
                        // 尝试解析为毫秒级时间戳
                        try {
                            long timestamp = Long.parseLong(date);
                            return new Date(timestamp);
                        } catch (NumberFormatException e3) {
                            // 如果所有解析方式都失败，返回当前时间
                            return new Date();
                        }
                    }
                }
            }
        }
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Date.class, new CustomDateDeserializer());
        objectMapper.registerModule(module);
        return objectMapper;
    }
}